<template lang="html">
  <article id="views-login">
    <button type="button" class="loginBtn" @click="loginTwitter">Twitter登录</button>
  </article>
</template>

<script>
import utils from '@/lib/utils'

export default {
  name: 'Page-login',
  data(){
    return {
      twitter: '',
      isTwitterLoading: false
    }
  },
  methods: {
    getTwitterLoginUrl(){
      return utils.requestFactory({ url: '/api/OAuth/twitter', params: { url: window.btoa(window.location.href) } })
    },
    setTwitter(){
      this.isTwitterLoading = true
      this.getTwitterLoginUrl()()
      .then(({ url }) => {
        this.isTwitterLoading = false
        this.twitter = url
      })
      .catch(e => {
        this.isTwitterLoading = false
        console.log(e);
      })
    },
    createTwitterWatcher(){
      return new Promise((resolve, reject) => {
        let unwatch = this.$watch('twitter', (val) => {
          if(val.length > 0){
            resolve(val)
            unwatch()
          } else {
            if(!this.isTwitterLoading){
              this.setTwitter()
            }
          }
        })
      })
    },
    getUserInfo(){
      return utils.requestFactory({ url: '/api/member/userinfo', type: 'post' })
    },
    loginTwitter(){
      this.$store.dispatch('toggleIsLoading')
      if(this.twitter.length > 0){
        this.$store.dispatch('toggleIsLoading')
        window.location.href = this.twitter
      } else {
        this.createTwitterWatcher()
        .then(url => {
          window.location.href = url
          this.$store.dispatch('toggleIsLoading')
        })
      }
    }
  },
  created(){
    this.setTwitter()

    this.getUserInfo()()
    .then(data => {
      console.log(data);
    })
    .catch(e => {
      if(e.status === 403){//无法获取token
      }
    })
  }
}
</script>

<style lang="scss">
#views-login{
  width: 100%;
  height: 100%;
  background-color: #fff;
  overflow: hidden;
  .loginBtn{
    display: block;
    margin: 20px auto 0;
    padding: 15px 20px;
    font-size: 35px;
    border: 2px solid #f04897;
    border-radius: 10px;
    &:active{
      opacity: 0.5;
    }
  }
}
</style>
